package com.newsappserver.userservice.config;

import com.newsappserver.userservice.defines.UserRole;
import com.newsappserver.userservice.entity.Timestamps;
import com.newsappserver.userservice.entity.UserEntity;
import com.newsappserver.userservice.repository.UserRepository;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.time.LocalDateTime;
import java.util.HashSet;

@Slf4j
@Configuration
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class AppConfig {
    PasswordEncoder passwordEncoder;

    // 程序启动时就创建一个管理员账户
    @Bean
    ApplicationRunner applicationRunner(UserRepository userRepository) {
        return args -> {
            if (userRepository.findByUsername("admin").isEmpty()) {
                var role = new HashSet<String>();
                role.add(UserRole.ADMIN.name());

                UserEntity userEntity = UserEntity.builder()
                        .name("ADMIN")
                        .username("admin")
                        // TODO：你自己定义
//                        .email("<place your own email address>")
                        .email("1690544550@qq.com")
                        .password(passwordEncoder.encode("admin")) // 密码是admin
                        .timestamps(Timestamps.builder()
                                .createdAt(LocalDateTime.now())
                                .updatedAt(LocalDateTime.now())
                                .build())
                        .build();
                userRepository.save(userEntity);

                log.warn("Created new user: {}, try to change default password: admin", userEntity);
            }
        };
    }
}
